package com.live.video.util;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;

/**
 * Description:
 * User: godd
 * Date: 2017-11-05
 * Time: 22:32
 */
public class MyUtils {
    private MyUtils() {

    }

    /**
     * map 转 bean
     *
     * @author 戴长春    dcc@vtc365.com
     * @date 2017/6/28 上午11:11
     */
    @Deprecated
    public static void transMap2Bean(Map<String, String> map, Object obj) {
        try {
            BeanUtils.populate(obj, map);
        } catch (Exception e) {
        }
    }

    /**
     * bean 转 map
     *
     * @author 戴长春    dcc@vtc365.com
     * @date 2017/6/28 上午11:11
     */
    public static Map<String, String> transBean2Map(Object obj) {
        Map<String, String> map = new HashMap<>();
        try {
            map = BeanUtils.describe(obj);
            if (map.containsKey("class")) {
                map.remove("class");
            }
        } catch (Exception e) {

        }
        return map;
    }

    public static Map<String, String> transBeanToMapExceptNull(Object obj) {
        Objects.requireNonNull(obj);
        Map<String, String> objMap = transBean2Map(obj);
        Set<Entry<String, String>> entries = objMap.entrySet();
        Iterator<Entry<String, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Entry<String, String> next = iterator.next();
            if (next.getKey() == null || next.getValue() == null) {
                iterator.remove();
            }
        }
        return objMap;
    }

    public static Map<String, Object> transBean2MapExceptNull(Object obj) {
        Map<String, Object> map = new HashMap<>();
        try {
            Class<?> _class = obj.getClass();
            Field[] _field = _class.getDeclaredFields();
            for (Field _f : _field) {
                String key = _f.getName();
                Method getter = _class.getMethod("get" + initcap(key));
                Object value = getter.invoke(obj);
                if (value != null) {
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 生成getter,setter时转换变量名用
     *
     * @author 戴长春    dcc@vtc365.com
     * @date 2017/8/15 下午3:11
     */
    private static String initcap(String name) {
        return name.substring(0, 1).toUpperCase() + name.substring(1);
    }
}
